//
//  ViewController.m
//  17-SandBoxHomeWork
//
//  Created by 曹曹 on 16/8/5.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "ViewController.h"
#import "Contacts.h"
#import "ContactsTableViewCell.h"
#import "DetailViewController.h"
#import "AddContactViewController.h"

#define kTableViewCellReuse @"reuse"

@interface ViewController () <UITableViewDelegate, UITableViewDataSource, AddContactViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) AddContactViewController *addVC;
@property (nonatomic, strong) NSMutableArray *contactsArray;
@property (nonatomic, copy) NSString *documentPath;
@property (nonatomic, copy) NSString *contactPath;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    [self getPaths];
    //[self fileManager];
    [self unarchiveContact];
}

- (void)getPaths {
    NSArray *documentPathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    _documentPath = [documentPathArray firstObject];
    _contactPath = [_documentPath stringByAppendingPathComponent:@"contacts.plist"];
}

- (void)archiveContact {
    [NSKeyedArchiver archiveRootObject:_contactsArray toFile:_contactPath];
}

- (void)unarchiveContact {
    NSArray *contactsArray = [NSKeyedUnarchiver unarchiveObjectWithFile:_contactPath];
    NSLog(@"===%@", _contactPath);
    _contactsArray = [[NSArray arrayWithArray:contactsArray] mutableCopy];
}

- (void)addContact:(Contacts *)contact {
    if (![contact.contactName isEqualToString:@""]) {
        [_contactsArray addObject:contact];
        [self archiveContact];
    }
    [self.tableView reloadData];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_contactsArray removeObjectAtIndex:indexPath.row];
        [self archiveContact];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_contactsArray) {
        return _contactsArray.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ContactsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellReuse];
    if (_contactsArray) {
        Contacts *contact = [_contactsArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = contact.contactName;
        NSString *imageName = contact.contactAvatar;
        cell.avatarView.image = [UIImage imageNamed:imageName];
    } else {
        cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([sender isKindOfClass:[ContactsTableViewCell class]]) {
        ContactsTableViewCell *cell = sender;
        DetailViewController *detailVC = segue.destinationViewController;
        NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
        detailVC.contact = _contactsArray[indexPath.row];
    } else {
        AddContactViewController *addContactVC = segue.destinationViewController;
        addContactVC.delegate = self;
    }
}

- (void)fileManager {
    /**
     实现文件、文件夹的基本操作(调研NSFileManager, 并实现以下功能)
     创建文件、文件夹
     删除文件、文件夹
     文件 是否存在
     移动文件
     拷贝文件
     */
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *documentPathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"documentPath-----%@", [documentPathArray firstObject]);
    // 创建文件夹
    NSString *directoyrPath0 = [[documentPathArray firstObject] stringByAppendingPathComponent:@"createdDirectory0"];
    NSString *directoryPath1 = [[documentPathArray firstObject] stringByAppendingPathComponent:@"createdDirectory1"];
    [manager createDirectoryAtPath:directoyrPath0 withIntermediateDirectories:YES attributes:nil error:nil];
    [manager createDirectoryAtPath:directoryPath1 withIntermediateDirectories:YES attributes:nil error:nil];
    // 创建文件
    NSString *filePath0 = [[documentPathArray firstObject] stringByAppendingPathComponent:@"createdFile0.txt"];
    NSString *filePath1 = [[documentPathArray firstObject] stringByAppendingPathComponent:@"createdFile1.txt"];
    NSData *fileData0 = [@"This is my first file" dataUsingEncoding:NSUTF8StringEncoding];
    NSData *fileData1 = [@"This is my secnd file" dataUsingEncoding:NSUTF8StringEncoding];
    [manager createFileAtPath:filePath0 contents:fileData0 attributes:nil];
    [manager createFileAtPath:filePath1 contents:fileData1 attributes:nil];
    // 在文件夹下创建文件
    NSString *newFilePath = [directoryPath1 stringByAppendingPathComponent:@"newFile.txt"];
    NSData *newFileData = [@"I'm in directory." dataUsingEncoding:NSUTF8StringEncoding];
    [manager createFileAtPath:newFilePath contents:newFileData attributes:nil];
    // 删除文件
    [manager removeItemAtPath:filePath0 error:nil];
    // 删除文件夹
    [manager removeItemAtPath:directoyrPath0 error:nil];
    // 文件是否存在
    BOOL isFile0Exists = [manager fileExistsAtPath:filePath0];
    BOOL isFile1Exists = [manager fileExistsAtPath:filePath1];
    if (isFile0Exists) {
        NSLog(@"file0 exists.");;
    } else {
        NSLog(@"file0 is not exist.");
    }
    if (isFile1Exists) {
        NSLog(@"file1 exists.");
    } else {
        NSLog(@"file1 is not exist.");
    }
    // 文件夹是否存在
    BOOL isDirectory0Exists = [manager fileExistsAtPath:directoyrPath0];
    BOOL isDirectory1Exists = [manager fileExistsAtPath:directoryPath1];
    if (isDirectory0Exists) {
        NSLog(@"directory0 exists.");
    } else {
        NSLog(@"directory0 is not exists");
    }
    if (isDirectory1Exists) {
        NSLog(@"directory1 exists.");
    } else {
        NSLog(@"directory1 is not exists");
    }
    // 文件夹移动
    NSString *tmpPath = NSTemporaryDirectory();
    NSLog(@"temporyPath-----%@", tmpPath);
    NSString *newDirectoryPath1 = [tmpPath stringByAppendingPathComponent:@"createdDirectory1"];
    [manager moveItemAtPath:directoryPath1 toPath:newDirectoryPath1 error:nil];
    // 文件移动
    NSString *newFilePath1 = [tmpPath stringByAppendingPathComponent:@"createdFile1.txt"];
    [manager moveItemAtPath:filePath1 toPath:newFilePath1 error:nil];
    // 文件拷贝
    NSString *copyFilePath1 = [[documentPathArray firstObject] stringByAppendingPathComponent:@"copyFilePath1.txt"];
    [manager copyItemAtPath:newFilePath1 toPath:copyFilePath1 error:nil];
    // 文件夹拷贝
    NSString *copyDirectoryPath1 = [[documentPathArray firstObject] stringByAppendingPathComponent:@"copyDirectoryPath1"];
    [manager copyItemAtPath:newDirectoryPath1 toPath:copyDirectoryPath1 error:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
